package com.yljk.yljkproject.ui;

import static com.yljk.homedoctor.view.ui.Home_Fragment.REQUEST_FOR_SCAN;
import static com.yljk.servicemanager.constants.RouterApi.QrCodeActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.core.LogisticsCenter;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alsk.rn.kit.RNKITTools;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCursorResult;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.push.EMPushConfig;
import com.hyphenate.push.EMPushHelper;
import com.hyphenate.push.EMPushType;
import com.hyphenate.push.PushListener;
import com.hyphenate.util.EMLog;
import com.plv.thirdpart.blankj.utilcode.util.ActivityUtils;
import com.previewlibrary.ZoomMediaLoader;
import com.umeng.message.PushAgent;
import com.yilijk.base.AppBase;
import com.yilijk.base.network.config.BaseConfig;
import com.yilijk.base.network.core.NetWorkService;
import com.yilijk.base.network.core.RetrofitManager;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.network.https.NetAttestationUtils;
import com.yilijk.base.oss.UploadOssUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ActivityManagerUtils;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.CommonUtils;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.RomUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;
import com.yljk.homedoctor.HomeUtils;
import com.yljk.live.common.utils.MediaCountyManager;
import com.yljk.mcconfig.constants.MCARouter;
import com.yljk.mydoctor.entity.VersionEntity;
import com.yljk.servicemanager.constants.ClickApi;
import com.yljk.servicemanager.constants.ConfigApi;
import com.yljk.servicemanager.constants.ReactApi;
import com.yljk.servicemanager.constants.RouterApi;
import com.yljk.servicemanager.constants.UrlApi;
import com.yljk.servicemanager.oldbase.ModuleBaseActivity;
import com.yljk.yljkproject.BuildConfig;
import com.yljk.yljkproject.MyApplication;
import com.yljk.yljkproject.R;
import com.yljk.yljkproject.adapter.PhoneAdapter;
import com.yljk.yljkproject.broadcast.NetWorkStateReceiver;
import com.yljk.yljkproject.entity.PopUpEntity;
import com.yljk.yljkproject.entity.TabEntity;
import com.yljk.yljkproject.manager.TestImageLoader;
import com.yljk.yljkproject.utils.EMMessageUtils;
import com.yljk.yljkproject.utils.PushUtils;
import com.yljk.yljkproject.utils.ReactUtils;
import com.yljk.yljkproject.utils.RomUtil;
import com.yljk.yljkproject.utils.UpgradeManager;
import com.yljk.yljkproject.widget.LogoutDialog;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import crossoverone.statuslib.StatusUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@Route(path = RouterApi.MAIN_ACTIVITY)
public class MainActivity extends ModuleBaseActivity {
    ArrayList<CustomTabEntity> tabs = new ArrayList<>();
    private Fragment home_fragment = null;
    private Fragment imDoctorFragment = null;
    //首页慧医学院
    private Fragment liveHomeFragment = null;
    private Fragment myFragment = null;
    public CommonTabLayout commontab;

    ArrayList<Fragment> fragments = new ArrayList<>();
    private FragmentManager fragmentManager;
    Handler handler = new Handler();
    private NetWorkStateReceiver netWorkStateReceiver;
    private LogoutDialog.Builder builder;
    private LogoutDialog logoutDialog;

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getBooleanExtra(ConfigApi.refreshMain, false)) {
                ALog.d("收到广播", "MainActivity收到刷新页面广播");
                commontab.setCurrentTab(0);
                getSupportFragmentManager().beginTransaction()
                        .hide(home_fragment)
                        .hide(imDoctorFragment)
                        .hide(liveHomeFragment)
                        .hide(myFragment)
                        .show(home_fragment)
                        .commitAllowingStateLoss();
            }
            if (intent.getBooleanExtra(ConfigApi.islogin, false)) {
                isLogout = true;
            }
            if (intent.getBooleanExtra(ConfigApi.isLogout, false)) {
                isLogout = true;
                onRestart();
            }
            if (intent.getBooleanExtra(ConfigApi.changeTab, false)) {
                int intExtra = intent.getIntExtra(ConfigApi.tabIndex, 0);
                viewpagerChange(intExtra);
                commontab.setCurrentTab(intExtra);
            }
        }
    };

    boolean isLogout = false;

    /**
     * 新版客服
     */
    private boolean clickormove = true;  //点击或拖动，点击为true，拖动为false
    private int downX, downY;   //按下时的X，Y坐标
    private int lastX, lastY;    //保存手指点下的点的坐标
    private int lastLeft, lastTop;    //记录上次滑动的左边距和上边距

    private int screenWidth, screenHeight;
    private FrameLayout main_layout;
    private FrameLayout imLayout;
    private ImageView custom_close;
    private PopupWindow popWindow;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        //隐藏状态栏
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //沉浸式设置
        StatusUtil.setSystemStatus(this, true, false);
        //如果是HMS设备 初始化华为推送
        if (RomUtil.isEmui()) {
            PushUtils.HMSUtils.getHMSPushToken(AppBase.getApplication());
            EMPushHelper.getInstance().setPushListener(new PushListener() {
                @Override
                public void onError(EMPushType pushType, long errorCode) {
                    EMLog.e("onError", "Push client occur a error: " + pushType + " - " + errorCode);
                }

                @Override
                public boolean isSupportPush(EMPushType pushType, EMPushConfig pushConfig) {
                    EMLog.e("isSupportPush", "Push client occur a error: " + pushType + " - " + pushConfig);
                    return super.isSupportPush(pushType, pushConfig);
                }
            });
        }
        //应用启动MainActivity onCreate 创建一次 埋点
        MediaCountyManager.getInstance().attachToRoot(this);
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        if (isLogout) {
            boolean b = SharedPreferencesUtils.getInstance().removeAll(this);
            if (b) {
                ARouter.getInstance().build(RouterApi.CenterActivity).navigation();
                isLogout = false;
                finish();
            }
        }
    }

    @Override
    protected void onPause() {
        alertDialog.dismiss();
        UploadOssUtils.getInstance().init();
        super.onPause();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //阿里上传
        UploadOssUtils.getInstance().init();
        //TODO 热、冷启动APP onShow统计
        ClickUtils.sendEvent("app_onshow", this);
        Intent intent = getIntent();
        if (intent != null) {
            setIntent(null);
            MyApplication.homeType = false;
            if (intent.hasExtra("tag")) {
                String tag = intent.getStringExtra("tag");
                switch (tag) {
                    //首页
                    case "jumpToHome": {
                        viewpagerChange(0);
                        commontab.setCurrentTab(0);
                    }
                    //消息列表
                    case "jumpToMsg": {
                        viewpagerChange(1);
                        commontab.setCurrentTab(1);
                    }
                    break;
                    //医生资质审核内容提交页面
                    case "jumpToDoctoCertify": {
                        Bundle bundle = new Bundle();
//                        bundle.putInt("notEdit", doctorDetailInfo.getPlatformAuditStatus());
                        bundle.putBoolean("azUseNew", true);
//                        bundle.putBoolean("azUseNew", doctorDetailInfo.isAzUseNew());
                        ReactUtils.INSTANCE.push(this, ReactApi.LOGIN_DOCTORBUNDLE, ReactApi.Login.QualificationPass, bundle);
                    }
                    break;
                    //实名认证页面
                    case "jumpToNameCertify": {
                        ReactUtils.INSTANCE.push(this, ReactApi.LOGIN_DOCTORBUNDLE, ReactApi.Login.AutonymApprovePage);
                    }
                    break;
                    //我的问诊页面
                    case "jumpToMyInquiry": {
                        ReactUtils.INSTANCE.push(this, ReactApi.IM_DOCTORBUNDLE, ReactApi.Message.MyPhysicianVisits);
                    }
                    break;
                    //处方管理
                    case "jumpToPrescriptions": {
                        ReactUtils.INSTANCE.push(this, ReactApi.LOGIN_DOCTORBUNDLE, ReactApi.Message.Prescriptions);
                    }
                    break;
                    //我的钱包
                    case "jumpToMoneyPackback": {
                        ReactUtils.INSTANCE.push(this, ReactApi.LOGIN_DOCTORBUNDLE, ReactApi.Mine.MyWalletPage);
                    }
                    break;
                    //客服（建议跳转修改银行卡信息页面）
                    case "jumpToEditbankcard": {
                        ReactUtils.INSTANCE.push(this, ReactApi.MY_DOCTORBUNDLE, ReactApi.Mine.Editbankcard);
                    }
                    break;
                    //我的评价
                    case "jumpToMyEvaluation": {
                        ReactUtils.INSTANCE.push(this, ReactApi.LOGIN_DOCTORBUNDLE, ReactApi.Mine.MyEvaluationandWall);
                    }
                    case "url": {
                        String urlLoad = intent.getStringExtra("urlLoad");
                        if (!TextUtils.isEmpty(urlLoad)) {
                            ARouter.getInstance().build(RouterApi.WebActivity)
                                    .withString("url", urlLoad)
                                    .withBoolean("ishtml", false)
                                    .withBoolean("isShowLoading", true)
                                    .navigation();
                        }
                    }
                    break;
                    case "jumpToQrCode": {
                        Postcard postcard = ARouter.getInstance()
                                .build(QrCodeActivity);
                        LogisticsCenter.completion(postcard);
                        Intent intent1 = new Intent(this, postcard.getDestination());
                        intent1.putExtras(postcard.getExtras());
                        startActivityForResult(intent1, REQUEST_FOR_SCAN);
                    }
                    break;
                }
            }
        } else {
            ALog.e("oakkkkkk", "hometype: " + MyApplication.homeType);
            if (MyApplication.homeType) {
                MyApplication.homeType = false;
                viewpagerChange(0);
                commontab.setCurrentTab(0);
            }
        }

    }

    @Override
    public int bondLayout() {
        return R.layout.activity_main;
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!CommonUtils.checkPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                requestPermissions(new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                }, 10001);
            }
            if (!CommonUtils.checkPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                requestPermissions(new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                }, 10001);
            }

        }
        fragmentManager = getSupportFragmentManager();
        PushAgent.getInstance(this).onAppStart();
        ZoomMediaLoader.getInstance().init(new TestImageLoader());
        //注册广播接收器
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BaseConfig.Receiver.BroadcastReceiver);
        registerReceiver(broadcastReceiver, intentFilter);
        if (netWorkStateReceiver == null) {
            netWorkStateReceiver = new NetWorkStateReceiver();
        }
        IntentFilter intentFilter1 = new IntentFilter();
        intentFilter1.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver, intentFilter1);
        commontab = findViewById(R.id.commontab);
        //添加底部导航icon
        tabs.clear();


//        if (SharedPreferencesUtils.getInstance().getString(AllStringConstants.token,null) == null){
//            Toast.makeText(this, "未登录，请先登录", Toast.LENGTH_SHORT).show();
//            ReactUtils.INSTANCE.push(this,ReactApi.LOGIN_DOCTORBUNDLE,ReactApi.Index);
//        }
        //初始化显示的页面
        //页面数据加载
        home_fragment = null;
        imDoctorFragment = null;
        liveHomeFragment = null;
        myFragment = null;
        //获取主页/im消息页 fragmetn
        home_fragment = (Fragment) ARouter.getInstance().build(RouterApi.HOME_FRAGMENT).navigation();
        liveHomeFragment = (Fragment) ARouter.getInstance().build(MCARouter.LIVE_HOME_TAB).navigation();
        imDoctorFragment = (Fragment) ARouter.getInstance().build(RouterApi.IMFRAGMENT).navigation();
        myFragment = (Fragment) ARouter.getInstance().build(ConfigApi.Open.isNewMine ? RouterApi.NewMineFragment : RouterApi.MineFragment).navigation();
        if (home_fragment != null) {
            fragmentManager.beginTransaction()
                    .add(R.id.main_viewpager, home_fragment)
                    .commit();
            fragments.add(home_fragment);
            tabs.add(new TabEntity(R.mipmap.main_home_select, R.mipmap.main_home_unselect, "首页"));
        }
        if (imDoctorFragment != null) {
            fragmentManager.beginTransaction()
                    .add(R.id.main_viewpager, imDoctorFragment)
                    .commit();
            fragments.add(imDoctorFragment);
            tabs.add(new TabEntity(R.mipmap.main_msg_select, R.mipmap.main_msg_unselect, "消息"));
        }
        if (liveHomeFragment != null) {
            fragmentManager.beginTransaction()
                    .add(R.id.main_viewpager, liveHomeFragment)
                    .commit();
            fragments.add(liveHomeFragment);
            tabs.add(new TabEntity(R.mipmap.live_home_select, R.mipmap.live_home_unselect, "慧医学院"));
        }
        if (myFragment != null) {
            fragmentManager.beginTransaction()
                    .add(R.id.main_viewpager, myFragment)
                    .commit();
            fragments.add(myFragment);
            tabs.add(new TabEntity(R.mipmap.main_mine_select, R.mipmap.main_mine_unselect, "我的"));
        }
        commontab.setTabData(tabs);

        /**
         * 新版客服
         */
        imLayout = findViewById(R.id.imLayout);
        main_layout = findViewById(R.id.main_layout);
        //初始设置一个layoutParams
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams((int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.2), (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.2));
        layoutParams.gravity = Gravity.BOTTOM | Gravity.END;
        imLayout.setLayoutParams(layoutParams);
        custom_close = findViewById(R.id.custom_close);
        initEvent();
        viewpagerChange(0);
        commontab.setCurrentTab(0);

    }


    @Override
    public void initData() {
        initLogoutAlert();
        initNewMessagePop();
        moveButton();
        getVersionCode();


    }


    /**
     * 新消息pop
     */

    private PopupWindow newMessagePop;
    View newMessagePopView;
    ImageView newMessagePopClose;
    TextView newMessagePopCheck;

    //
    private void initNewMessagePop() {
        newMessagePop = new PopupWindow();
        newMessagePopView = LayoutInflater.from(this).inflate(R.layout.new_message_pop, null);
        newMessagePopClose = (ImageView) newMessagePopView.findViewById(R.id.new_message_pop_close);
        newMessagePopCheck = (TextView) newMessagePopView.findViewById(R.id.new_message_pop_check);

        newMessagePop.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        newMessagePop.setHeight(LinearLayout.LayoutParams.MATCH_PARENT);
        newMessagePop.setContentView(newMessagePopView);

        newMessagePop.setFocusable(false);
        newMessagePop.setOutsideTouchable(false);
        newMessagePop.setOnDismissListener(() -> CommonUtils.setBackgroundAlpha(MainActivity.this, 1.0f));
        newMessagePopClose.setOnClickListener(v -> newMessagePop.dismiss());
        newMessagePopCheck.setOnClickListener(v -> {
            commontab.setCurrentTab(1);
            viewpagerChange(1);
            imLayout.setVisibility(View.GONE);
            newMessagePop.dismiss();
        });
    }


    /**
     * 异地登录
     */

//    @ThreadConfined(UI)
    void logoutDialogShow() {
        handler.post(() -> {
//                Activity lastestActivity = ActivityManagerUtils.getLastestActivity();
//                if (lastestActivity == null) return;
            builder = new LogoutDialog.Builder(ActivityUtils.getTopActivity());
            builder.setMessage("您的账号已在其他设备登录，请注意账号安全。");
            builder.setTitle("登录断开");

            builder.setPositiveButton("确定", (dialog, which) -> {
                //设置你的操作事项
                NetAttestationUtils.getInstance().setSALT("");
                ActivityManagerUtils.finishAllActivity();
                SharedPreferencesUtils.getInstance().removeAll(MainActivity.this);
                ARouter.getInstance().build(RouterApi.CenterActivity).navigation();
                dialog.dismiss();
                finish();
            });
            logoutDialog = builder.create();
            logoutDialog.setCancelable(false);
            if (!logoutDialog.isShowing() && !isDestroyed()) {
                logoutDialog.show();
            }
        });
    }

    /**
     * 新消息弹窗
     */
    void showNewMessagePop() {
//        newMessagePop.showAsDropDown(getLayoutInflater().inflate(R.layout.activity_main,null),0,0,Gravity.CENTER);

        handler.post(() -> {
            newMessagePop.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
            CommonUtils.setBackgroundAlpha(newMessagePop, MainActivity.this, 0.3f);
        });
    }

    /**
     * 获取最新版本号，判断是否需要更新版本
     */
    private void getVersionCode() {
//        if (DevicesUtils.isChannel()) {
//            return;
//        }
        // 获得存储卡的路径
//        String sdpath = Environment.getExternalStorageDirectory().getPath();
//        String mSavePath = sdpath + "/com.yljk.yljkproject";

        String mSavePath = getExternalFilesDir("apk").getAbsolutePath();
        ALog.e("updateOak", "downAPK mSavePath: " + mSavePath);

        ALog.d("chen", "apk包下载路径为" + mSavePath);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), CommonUtils.getModuleCommonUtils().getMaptoJson(new HashMap<>()));
        Call<ResponseBody> netWorkJson = RetrofitManager.getRetrofitManager().getRetrofit().create(NetWorkService.class).post(UrlApi.downApk, requestBody);
        netWorkJson.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                try {
                    if (response.body() == null) {
                        return;
                    }
                    String string = response.body().string();
                    ALog.d("LAE", "onResponse: response=" + string);
                    VersionEntity versionEntity = new Gson().fromJson(string, VersionEntity.class);
                    if (versionEntity.getCode() == 401) {
                        isLogout = true;
                        onRestart();
                    }
                    if (request_result(versionEntity.getStatus())) {
                        return;
                    }
                    if (versionEntity.getCode() != 200) {
                        return;
                    }
                    VersionEntity.DataBean data = new Gson().fromJson(string, VersionEntity.class).getData();
                    ALog.e("updateOak", "downAPK version: " + DevicesUtils.getVersionCode() + " " + data.getVersion());
                    if (DevicesUtils.getVersionCode() >= data.getVersion()) {
                        return;
                    }
                    UpgradeManager.UpdateFlag updateFlag = UpgradeManager.UpdateFlag.UN_UPDATE;
                    // 渠道包检查是否更新
                    if (DevicesUtils.isChannel()) {
                        if (RomUtils.isHuawei() && Boolean.parseBoolean(data.getHuawei_isstrong())) {
                            //华为手机的渠道包是否更新
                            updateFlag = UpgradeManager.UpdateFlag.UPDATE_FLAG_HUAWEI;
                        } else if (RomUtils.isXiaomi() && Boolean.parseBoolean(data.getXiaomi_isstrong())) {
                            //小米手机的渠道包是否更新
                            updateFlag = UpgradeManager.UpdateFlag.UPDATE_FLAG_XIAOMI;
                        } else if (RomUtils.isVivo() && Boolean.parseBoolean(data.getVivo_isstrong())) {
                            //VIVO手机的渠道包是否更新
                            updateFlag = UpgradeManager.UpdateFlag.UPDATE_FLAG_VIVO;
                        } else if (RomUtils.isOppo() && Boolean.parseBoolean(data.getOppo_isstrong())) {
                            //OPPO手机的渠道包是否更新
                            updateFlag = UpgradeManager.UpdateFlag.UPDATE_FLAG_OPPO;
                        }

                    } else {
                        //官网是否更新
                        if (Boolean.parseBoolean(data.getGuanwang_isstrong())) {
                            updateFlag = UpgradeManager.UpdateFlag.UPDATE_FLAG_GUANWANG;
                        }
                    }
                    if (updateFlag == UpgradeManager.UpdateFlag.UN_UPDATE) {
                        return;
                    }
                    // 检查软件更新
                    UpgradeManager manager = new UpgradeManager(MainActivity.this, mSavePath, data.getVersion(), data.getUrl(), updateFlag, Boolean.parseBoolean(data.getIsstrong()), data.getContent());
                    manager.checkUpdate();
//                    handler.sendEmptyMessage(2);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
            }
        });
    }

    private boolean request_result(String code) {
        return CommonUtils.request_code(MainActivity.this, code);
    }

    private AlertDialog alertDialog;

    private void initLogoutAlert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        alertDialog = builder.setTitle("退出提示")
                .setIcon(R.mipmap.app_logo)
                .setMessage("退出后可能无法及时收到患者信息，是否确认退出?")
                .setPositiveButton("确定", (dialog, which) -> finish())
                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                .create();
    }


    //监听
    @Override
    public void initEvent() {
        custom_close.setOnClickListener(v -> imLayout.setVisibility(View.GONE));
        //IM链接监听
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
        //注册一个监听连接状态的listener
        EMClient.getInstance().addConnectionListener(myEMConnectionListener);
        //退出登录确定监听
        //底部导航的点击监听
        commontab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                imLayout.setVisibility(View.VISIBLE);
                MediaCountyManager.getInstance().tabSelect(MainActivity.this, position, 2);
                switch (position) {
                    case 0:
                        ClickUtils.sendEvent(ClickApi.App.Tab_Home, MainActivity.this, "首页Tab点击");
                        viewpagerChange(0);
                        break;
                    case 1:
                        ClickUtils.sendEvent(ClickApi.App.Tab_Mine, MainActivity.this, "我的Tab点击");
                        viewpagerChange(1);
                        imLayout.setVisibility(View.GONE);
                        break;
                    case 2:
                        ClickUtils.sendEvent(ClickApi.App.Tab_Live, MainActivity.this, "智慧学院Tab点击");
                        viewpagerChange(2);
                        imLayout.setVisibility(View.GONE);
                        break;
                    case 3:
                        ClickUtils.sendEvent(ClickApi.App.Tab_Mine, MainActivity.this, "我的Tab点击");
                        viewpagerChange(3);
                        break;
                }
            }

            @Override
            public void onTabReselect(int position) {
            }
        });

        //展开收起popupwindows
        imLayout.setOnClickListener(view -> {

//                AGConnectCrash.getInstance().testIt(MainActivity.this);
            if (clickormove) {
                if (popWindow == null) {
                    initPopWindow();
                } else {
                    if (popWindow.isShowing()) {
                        popWindow.dismiss();
                    } else {
                        popWindow.showAsDropDown(imLayout, -(int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.15), -(int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.44));
                    }
                }
            }
        });
        if (BuildConfig.OPEN_LOG) {
//        if (true){
            imLayout.setOnLongClickListener(v -> {
                startActivity(new Intent(MainActivity.this, RNDebugActivity.class));
//                    AppMarketUtil.getInstance().callHuaweiAppDetail(getPackageName(),MainActivity.this);
//                    AppMarketUtil.getInstance().callXiaomiAppDetail(getPackageName(),MainActivity.this);
//                    AppMarketUtil.getInstance().callOppoAppDetail(getPackageName(),MainActivity.this);
//                    AppMarketUtil.getInstance().callVivoAppDetail(getPackageName(),MainActivity.this);
                return false;
            });
        }


    }

    /**
     * 消息监听反注册
     * 广播注销
     */
    @Override
    protected void onDestroy() {
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
        unregisterReceiver(broadcastReceiver);
        if (netWorkStateReceiver != null) {
            unregisterReceiver(netWorkStateReceiver);
        }
        super.onDestroy();
    }

    //viewpager hide show 切换显示
    public void viewpagerChange(int showPasition) {
        if (!fragments.isEmpty()) {
            for (int i = 0; i < fragments.size(); i++) {
                Fragment fragment = fragments.get(i);
                if (i == showPasition) {
                    fragmentManager.beginTransaction().show(fragment)
                            .setMaxLifecycle(fragment, Lifecycle.State.RESUMED)
                            .commit();
                } else {
                    fragmentManager.beginTransaction().hide(fragment)
                            .setMaxLifecycle(fragment, Lifecycle.State.STARTED).commit();
                }
            }
        } else {
            ALog.d("viewpagerChange", "fragments must not empty: ");
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!alertDialog.isShowing()) {
                alertDialog.show();
            }
        }
        return false;
    }

    /**
     * IM监听
     * <p>
     * 消息监听
     * <p>
     * 连接状态监听
     */
    //IM消息监听
    EMMessageListener msgListener = new EMMessageListener() {
        @SuppressLint("WrongConstant")
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            if (imDoctorFragment.isHidden() && !newMessagePop.isShowing() && messages.size() > 0 && messages.get(0).getChatType() == EMMessage.ChatType.Chat) {
                HttpUtils.get(UrlApi.popUp, new HttpCallBack<PopUpEntity>() {
                    @Override
                    public void onSuccess(PopUpEntity popUpEntity, int code) {
                        if (popUpEntity.isResult() && popUpEntity.getData() != null) {
                            if (popUpEntity.getData().isNeedPopUp()) {
                                showNewMessagePop();
                            }
                        }
                    }

                    @Override
                    public void onFailure(String failureMsg, int statusCode) {

                    }
                });
            }

            //收到消息
            ALog.i("IM收到", "onMessageReceived: " + messages.get(0).toString());
            ALog.i("IM收到", "onMessageReceived: " + messages.get(0).ext().toString());
//            sendChatMsg();
            Intent intent = new Intent(BaseConfig.Receiver.BroadcastReceiver);
            intent.putExtra(ConfigApi.receiverMsg, true);
            intent.putExtra(ConfigApi.receiverUser, messages.get(0).getFrom());
            intent.putExtra(ConfigApi.refreshHome_getChargeData, true);
            //向广播接收器传递数据
            sendBroadcast(intent);      //发送广播
            for (int i = 0; i < messages.size(); i++) {
                String s = EMMessageUtils.emMessageJson(messages.get(i), false);
                ALog.i("onMessageReceived", "onMessageReceived: " + s);
                RNKITTools.INSTANCE.sendBroadcast(MainActivity.this, "ReceiveOrdinaryChatMessage", s);
            }

        }

        @SuppressLint("WrongConstant")
        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //收到透传消息

            for (int i = 0; i < messages.size(); i++) {
                String s = EMMessageUtils.emMessageJson(messages.get(i), false);
                ALog.i("onMessageReceived", "onMessageReceived: " + s);
                EMMessage emMessage = messages.get(i);
                String from = emMessage.getFrom();
                try {
                    EMCursorResult<EMMessage> emMessageEMCursorResult = EMClient.getInstance().chatManager().fetchHistoryMessages(from, EMConversation.EMConversationType.Chat, 2, null);
                    EMMessage emMessage1 = emMessageEMCursorResult.getData().get(0);
                    ALog.i("IM收到", "onCmdMessageReceived: " + emMessage1.toString());
                    ALog.i("IM收到", "onCmdMessageReceived: " + emMessage1.ext().toString());
                    String s1 = EMMessageUtils.emMessageJson(emMessage1, false);
                    RNKITTools.INSTANCE.sendBroadcast(MainActivity.this, "ReceiveOrdinaryChatMessage", s1);
                    Intent intent = new Intent(BaseConfig.Receiver.BroadcastReceiver);
                    intent.putExtra(ConfigApi.receiverCMDMsg, true);
                    intent.putExtra(ConfigApi.receiverUser, from);
//                    //向广播接收器传递数据
                    sendBroadcast(intent);      //发送广播
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }

            }
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            //收到已读回执
            ALog.i("IM收到", "onMessageRead: ");
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            //收到已送达回执
            ALog.i("IM收到", "onMessageDelivered: ");
//            Intent intent = new Intent(AllStringConstants.BroadcastReceiver);
//            intent.putExtra(AllStringConstants.refreshIM, true);
//            intent.putExtra(AllStringConstants.imFrom, message.get(0).getFrom());
//            intent.putExtra(AllStringConstants.refreshHome_getChargeData, true);
            //向广播接收器传递数据
//            sendBroadcast(intent);      //发送广播
        }

        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
            //消息被撤回
            for (int i = 0; i < messages.size(); i++) {
                Intent intent = new Intent(BaseConfig.Receiver.BroadcastReceiver);
                intent.putExtra(ConfigApi.refreshRecall, true);         //向广播接收器传递数据
                intent.putExtra(ConfigApi.recallMessage, 0);         //向广播接收器传递数据
                intent.putExtra(ConfigApi.receiverUser, messages.get(i).getFrom());         //向广播接收器传递数据
                sendBroadcast(intent);      //发送广播
                String s = EMMessageUtils.emMessageJson(messages.get(i), true);
                RNKITTools.INSTANCE.sendBroadcast(MainActivity.this, "ReceiveOrdinaryChatMessage", s);
            }
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //消息状态变动
            ALog.i("IM收到", "onMessageChanged: ");
        }
    };

    //连接状态的监听
    EMConnectionListener myEMConnectionListener = new EMConnectionListener() {
        @Override
        public void onConnected() {

        }

        @Override
        public void onDisconnected(int errorcode) {
            if (errorcode == EMError.USER_REMOVED) {

            } else if (errorcode == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                //账号在其他设备登录
                logoutDialogShow();
            } else if (errorcode == EMError.SERVER_SERVICE_RESTRICTED) {

            } else if (errorcode == EMError.USER_KICKED_BY_CHANGE_PASSWORD) {
                //账号在其他设备登录

                logoutDialogShow();
            } else if (errorcode == EMError.USER_KICKED_BY_OTHER_DEVICE) {
                //账号被其他设备踢出
                logoutDialogShow();
            }
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //
        if (requestCode == 10001) {//如果申请权限回调的参数
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                String sdpath = Environment.getExternalStorageDirectory().getPath();
                String mSavePath = sdpath + "/com.yljk.yljkproject";
                ALog.d("chen", "apk包下载路径为" + mSavePath);
                // 判断文件目录是否存在
                File noMedia = new File(mSavePath);
                if (!noMedia.exists()) {
                    noMedia.mkdirs();
                    try {
                        noMedia.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
//                getVersionCode();//取得权限重新获取更新版本接口
                MediaCountyManager.getInstance().onGranted();
                return;

            }
            String sdpath = Environment.getExternalStorageDirectory().getPath();
            String mSavePath = sdpath + "/com.yljk.yljkproject";
            ALog.d("chen", "apk包下载路径为" + mSavePath);
            // 判断文件目录是否存在
            File noMedia = new File(mSavePath);
            if (!noMedia.exists()) {
                noMedia.mkdirs();
                try {
                    noMedia.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @SuppressLint("ClickableViewAccessibility")
    void moveButton() {
        //控制客服聊天拖动
        DisplayMetrics dm = getResources().getDisplayMetrics();//获取显示屏属性
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels - commontab.getHeight();
        ALog.i("moveButton", "moveButton: " + dm.heightPixels);
        ALog.i("moveButton", "moveButton: " + screenHeight);
        //设置按钮被触摸的时间
        imLayout.setOnTouchListener((view, event) -> {

            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    //将点下的点的坐标保存
                    lastX = (int) event.getRawX();
                    lastY = (int) event.getRawY();
                    downX = lastX;
                    downY = lastY;
                    break;

                case MotionEvent.ACTION_MOVE:
                    //计算出需要移动的距离
                    int dx = (int) event.getRawX() - lastX;
                    int dy = (int) event.getRawY() - lastY;
                    //将移动距离加上，现在本身距离边框的位置
                    int left = view.getLeft() + dx;
                    int top = view.getTop() + dy;
                    int right = view.getRight() + dx;
                    int bottom = view.getBottom() + dy;
                    if (left < 0) {
                        left = 0;
                        right = left + view.getWidth();
                    }
                    if (right > screenWidth) {
                        right = screenWidth;
                        left = right - view.getWidth();
                    }
                    if (top < 0) {
                        bottom = top + view.getHeight();
                    }
                    if (bottom > screenHeight) {
                        bottom = screenHeight;
                        top = bottom - view.getHeight();
                    }
                    //获取到layoutParams然后改变属性，在设置回去
                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) view
                            .getLayoutParams();
                    layoutParams.gravity = 0;
                    layoutParams.height = (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.2);
                    layoutParams.width = (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.2);
                    layoutParams.leftMargin = left;
                    layoutParams.topMargin = top;
                    view.setLayoutParams(layoutParams);
                    lastX = (int) event.getRawX();
                    lastY = (int) event.getRawY();
                    lastTop = top;
                    lastLeft = left;
                    break;
                case MotionEvent.ACTION_UP: // 弹起事件
                    //判断是单击事件或是拖动事件，位移量大于5则断定为拖动事件
                    if (Math.abs((int) (event.getRawX() - downX)) > 5 || Math.abs((int) (event.getRawY() - downY)) > 5) {
                        clickormove = false;
//                            if (lastTop < (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.28) || lastLeft < (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.15)) {//需要判断滑到最顶部时 退回一定距离，给popupwindow流出空隙
                        FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) view
                                .getLayoutParams();
                        layoutParams1.gravity = 0;
                        layoutParams1.height = (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.2);

                        layoutParams1.width = (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.2);

                        layoutParams1.topMargin = Math.max(lastTop, (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.28));
//                                if (lastLeft < (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.15)) {
//                                    layoutParams1.leftMargin = (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.15);
//                                } else {
//                                    layoutParams1.leftMargin = lastLeft;
//                                }
                        if (lastLeft < (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.5)) {
                            layoutParams1.leftMargin = 0;
                        } else {
                            layoutParams1.leftMargin = (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.8);
                        }
                        view.setLayoutParams(layoutParams1);
//                            }
                    } else {

                        clickormove = true;
                    }
                    break;
            }
            //刷新界面
            main_layout.invalidate();
            return false;
        });
    }

    RecyclerView phoneList;
    TextView cancelDialog;

    @SuppressLint("NotifyDataSetChanged")
    private void openPhoneView(ArrayList<String> tels) {
        PopupWindow popupWindow = new PopupWindow();
        popupWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        @SuppressLint("InflateParams")
        View inflate = LayoutInflater.from(this).inflate(R.layout.phone_dialog_layout, null);
        phoneList = (RecyclerView) inflate.findViewById(R.id.phone_list);
        cancelDialog = (TextView) inflate.findViewById(R.id.cancel_dialog);
        PhoneAdapter phoneAdapter = new PhoneAdapter(R.layout.item_phone, tels);
        phoneList.setLayoutManager(new LinearLayoutManager(this));
        phoneList.setAdapter(phoneAdapter);
        phoneAdapter.notifyDataSetChanged();
        popupWindow.setContentView(inflate);
        popupWindow.setAnimationStyle(R.style.popwindow_anim_style);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.5f);
        popupWindow.setOnDismissListener(() -> backgroundAlpha(1.0f));
        cancelDialog.setOnClickListener(v -> popupWindow.dismiss());
        phoneAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (!CommonUtils.checkPermission(MainActivity.this, Manifest.permission.CALL_PHONE)) {
                CommonUtils.getModuleCommonUtils().setRequestPermission(MainActivity.this, new String[]{
                        Manifest.permission.CALL_PHONE,
                }, 10001);
            } else {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:" + tels.get(position)));
//                    开启系统拨号器
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

    }

    private void backgroundAlpha(float f) {
        WindowManager.LayoutParams attributes = getWindow().getAttributes();
        attributes.alpha = f;
        getWindow().setAttributes(attributes);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initPopWindow() {
        @SuppressLint("InflateParams")
        View view = LayoutInflater.from(this).inflate(R.layout.item_popup, null, false);
        LinearLayout tocontact_layout = (LinearLayout) view.findViewById(R.id.tocontact_layout);
        LinearLayout tophone_layout = (LinearLayout) view.findViewById(R.id.tophone_layout);
        //1.构造一个PopupWindow，参数依次是加载的View，宽高
        popWindow = new PopupWindow(view,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

//        popWindow.setAnimationStyle(R.anim.anim_pop);  //设置加载动画

        //这些为了点击非PopupWindow区域，PopupWindow会消失的，如果没有下面的
        //代码的话，你会发现，当你把PopupWindow显示出来了，无论你按多少次后退键
        //PopupWindow并不会关闭，而且退不出程序，加上下述代码可以解决这个问题
        popWindow.setTouchable(true);
        popWindow.setTouchInterceptor((v13, event) -> {
            return false;
            // 这里如果返回true的话，touch事件将被拦截
            // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
        });
        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));    //要为popWindow设置一个背景才有效


        //设置popupWindow显示的位置，参数依次是参照View，x轴的偏移量，y轴的偏移量
        popWindow.showAsDropDown(imLayout, -(int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.15), -(int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.44));

        //在线客服
        ClickUtils.setFastOnClickListener(tocontact_layout, v1 -> ARouter.getInstance().build(RouterApi.WebActivity)
                .withString("title", "在线客服")
                .withBoolean("ishtml", false)
                .withBoolean("isCustomor", true)
                .withBoolean("isShowLoading", true).navigation());
        //电话咨询
        ClickUtils.setFastOnClickListener(tophone_layout, v12 -> {
            ArrayList<String> tels = new ArrayList<>();
            tels.add("呼叫\t\t4000866316");
            openPhoneView(tels);
            popWindow.dismiss();
        });
    }


}